<template>
  <div
    class="sales-outbound-add-page"
    v-loading="pageLoading"
    element-loading-text="页面加载中..."
  >
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <el-icon class="breadcrumb-icon">
            <Box />
          </el-icon>
          <div>
            <p class="breadcrumb-subtitle">仓库管理 · 销售出库</p>
            <h2 class="breadcrumb-heading">
              {{ isEdit ? "编辑" : "新增" }}销售出库
            </h2>
          </div>
        </div>
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/SalesOutboundList' }">
            销售出库
          </el-breadcrumb-item>
          <el-breadcrumb-item>
            {{ isEdit ? "编辑" : "新增" }}销售出库
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <div class="status-overview">
      <div class="status-card">
        <div class="status-card__icon primary">
          <el-icon><Document /></el-icon>
        </div>
        <div class="status-card__body">
          <p class="status-card__label">当前单号</p>
          <h3 class="status-card__value">
            {{ formData.outboundNo || "待生成" }}
          </h3>
          <span class="status-card__hint">
            {{ formData.systemGenerated ? "系统自动生成" : "自定义编号" }}
          </span>
        </div>
      </div>
      <div class="status-card">
        <div class="status-card__icon success">
          <el-icon><User /></el-icon>
        </div>
        <div class="status-card__body">
          <p class="status-card__label">客户信息</p>
          <h3 class="status-card__value">
            {{ formData.customerName || "待选择客户" }}
          </h3>
          <span class="status-card__hint">
            销售单号：{{ formData.salesOrderNo || "未填写" }}
          </span>
        </div>
      </div>
      <div class="status-card">
        <div class="status-card__icon warning">
          <el-icon><Timer /></el-icon>
        </div>
        <div class="status-card__body">
          <p class="status-card__label">计划出库</p>
          <h3 class="status-card__value">
            {{ formatDisplayDate(formData.outboundDate) }}
          </h3>
          <span class="status-card__hint">
            预计数量：{{ formData.totalQuantity || 0 }}
          </span>
        </div>
      </div>
    </div>

    <el-card shadow="never" class="steps-card">
      <el-steps :active="currentStep" align-center>
        <el-step title="填写基本信息" description="编号、检验单、销售单" />
        <el-step title="确认客户与批次" description="关联客户、批次号" />
        <el-step title="完善出库明细" description="出库数量与仓库" />
      </el-steps>
    </el-card>

    <div class="content-layout">
      <div class="content-main">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="sales-outbound-form"
        >
          <!-- 基本信息 -->
          <el-card shadow="never" class="form-card">
            <template #header>
              <div class="card-header">
                <el-icon class="card-icon"><Document /></el-icon>
                <span class="card-title">基本信息</span>
              </div>
            </template>

            <div class="basic-info-wrapper">
              <el-row :gutter="24">
                <el-col :span="12">
                  <div class="inline-switch-field">
                    <el-form-item
                      label="出库单编号"
                      prop="outboundNo"
                      class="basic-form-item"
                    >
                      <template #label>
                        <span class="required-label">* 出库单编号</span>
                      </template>
                      <el-input
                        v-model="formData.outboundNo"
                        placeholder="请输入或自动生成"
                        :readonly="formData.systemGenerated"
                      />
                    </el-form-item>
                    <div class="inline-switch">
                      <el-switch
                        v-model="formData.systemGenerated"
                        size="small"
                        @change="handleSystemGeneratedChange"
                      />
                      <span class="inline-switch__text">
                        {{
                          formData.systemGenerated ? "系统编号" : "自定义编号"
                        }}
                      </span>
                      <el-button
                        text
                        type="primary"
                        :icon="DocumentCopy"
                        class="inline-copy"
                        @click="handleCopyOutboundNo"
                      >
                        复制
                      </el-button>
                    </div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="出库单名称"
                    prop="outboundName"
                    class="basic-form-item"
                  >
                    <template #label>
                      <span class="required-label">* 出库单名称</span>
                    </template>
                    <el-input
                      v-model="formData.outboundName"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item
                    label="出货检验单"
                    prop="inspectionOrderName"
                    class="basic-form-item"
                  >
                    <template #label>
                      <span class="required-label">* 出货检验单</span>
                    </template>
                    <el-input
                      v-model="formData.inspectionOrderName"
                      placeholder="请选择出货检验单"
                      readonly
                    >
                      <template #append>
                        <el-button
                          :icon="Search"
                          @click="handleSelectInspection"
                        />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="出货检验单号"
                    prop="inspectionOrderNo"
                    class="basic-form-item"
                  >
                    <el-input
                      v-model="formData.inspectionOrderNo"
                      placeholder="请选择出货检验单号"
                      readonly
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item
                    label="出库日期"
                    prop="outboundDate"
                    class="basic-form-item"
                  >
                    <el-date-picker
                      v-model="formData.outboundDate"
                      type="date"
                      placeholder="请选择日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                      :prefix-icon="Calendar"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="销售单号"
                    prop="salesOrderNo"
                    class="basic-form-item"
                  >
                    <template #label>
                      <span class="required-label">* 销售单号</span>
                    </template>
                    <el-input
                      v-model="formData.salesOrderNo"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item
                    label="客户名称"
                    prop="customerName"
                    class="basic-form-item"
                  >
                    <el-input
                      v-model="formData.customerName"
                      placeholder="请选择客户名称"
                      readonly
                    >
                      <template #append>
                        <el-button
                          :icon="Search"
                          @click="handleSelectCustomer"
                        />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="出库数量"
                    prop="totalQuantity"
                    class="basic-form-item"
                  >
                    <el-input
                      v-model="formData.totalQuantity"
                      placeholder="系统自动汇总"
                      readonly
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item label="备注" class="basic-form-item">
                    <el-input
                      v-model="formData.remark"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入"
                      maxlength="500"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-card>

          <!-- 出库明细 -->
          <el-card shadow="never" class="form-card">
            <template #header>
              <div class="card-header">
                <el-icon class="card-icon"><List /></el-icon>
                <span class="card-title">出库明细</span>
              </div>
            </template>

            <div v-if="formData.details[0]" class="detail-panel">
              <div class="detail-panel__header">
                <div>
                  <p class="detail-panel__title">产品出库信息</p>
                  <p class="detail-panel__desc">
                    参考纸质单据从左到右依次填写，与图示布局保持一致。
                  </p>
                </div>
                <div class="detail-panel__summary">
                  <span>出库数量：{{ formData.totalQuantity || 0 }}</span>
                </div>
              </div>

              <el-row :gutter="24" class="detail-grid compact">
                <el-col :span="12">
                  <el-form-item
                    label="产品名称"
                    class="detail-form-item"
                    prop="details.0.productName"
                  >
                    <el-input
                      v-model="formData.details[0].productName"
                      placeholder="请输入产品名称"
                      @blur="validateDetailField(0, 'productName')"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="产品编号"
                    class="detail-form-item"
                    prop="details.0.productNo"
                  >
                    <el-input
                      v-model="formData.details[0].productNo"
                      placeholder="请输入产品编号"
                      @blur="validateDetailField(0, 'productNo')"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="规格型号" class="detail-form-item">
                    <el-input
                      v-model="formData.details[0].specification"
                      placeholder="请输入规格型号"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="单位" class="detail-form-item">
                    <el-input
                      v-model="formData.details[0].unit"
                      placeholder="请输入单位"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="生产日期" class="detail-form-item">
                    <el-date-picker
                      v-model="formData.details[0].productionDate"
                      type="date"
                      placeholder="请选择生产日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="到期日期" class="detail-form-item">
                    <el-date-picker
                      v-model="formData.details[0].expiryDate"
                      type="date"
                      placeholder="请选择到期日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="批次号" class="detail-form-item">
                    <el-input
                      v-model="formData.details[0].batchNo"
                      placeholder="请选择批次号"
                      readonly
                    >
                      <template #append>
                        <el-button
                          :icon="Search"
                          size="small"
                          @click="handleSelectBatch(0)"
                        />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="出库数量" class="detail-form-item">
                    <el-input-number
                      v-model="formData.details[0].outboundQuantity"
                      :min="0"
                      :precision="2"
                      placeholder="请输入"
                      style="width: 100%"
                      @change="handleQuantityChange"
                      @blur="validateDetailField(0, 'outboundQuantity')"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="仓库名称" class="detail-form-item">
                    <el-input
                      v-model="formData.details[0].warehouseName"
                      placeholder="请选择仓库"
                      readonly
                    >
                      <template #append>
                        <el-button
                          :icon="Search"
                          size="small"
                          @click="handleSelectWarehouse(0)"
                        />
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="仓库负责人" class="detail-form-item">
                    <el-input
                      v-model="formData.details[0].warehouseManager"
                      placeholder="请输入负责人"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <el-empty
              v-else
              class="detail-empty"
              description="暂无可编辑的明细，请刷新重试"
            />
          </el-card>

          <!-- 操作按钮 -->
          <el-affix :offset="20" position="bottom" class="form-actions-affix">
            <div class="form-actions">
              <el-button @click="handleCancel">取消</el-button>
              <el-button
                type="primary"
                :loading="submitLoading"
                @click="handleSubmit"
              >
                确定
              </el-button>
            </div>
          </el-affix>
        </el-form>
      </div>
      <div class="content-aside">
        <el-card shadow="never" class="insight-card progress-card">
          <template #header>
            <div class="card-header">
              <el-icon class="card-icon"><Timer /></el-icon>
              <span class="card-title">流程进度</span>
            </div>
          </template>
          <div class="progress-body">
            <el-progress
              type="circle"
              :percentage="completionPercent"
              :stroke-width="10"
              :width="132"
              :color="progressColor"
            />
            <div class="progress-info">
              <p class="progress-value">{{ completionPercent }}%</p>
              <p class="progress-text">{{ nextActionText }}</p>
            </div>
          </div>
          <ul class="checklist">
            <li
              v-for="step in checklistSteps"
              :key="step.label"
              :class="['checklist-item', { done: step.complete }]"
            >
              <el-icon
                class="checklist-icon"
                :class="step.complete ? 'success' : 'pending'"
              >
                <CircleCheckFilled v-if="step.complete" />
                <WarningFilled v-else />
              </el-icon>
              <div>
                <p class="checklist-label">{{ step.label }}</p>
                <p class="checklist-desc">{{ step.description }}</p>
              </div>
            </li>
          </ul>
        </el-card>

        <el-card shadow="never" class="insight-card highlight-card">
          <template #header>
            <div class="card-header">
              <el-icon class="card-icon"><List /></el-icon>
              <span class="card-title">出库概览</span>
            </div>
          </template>
          <div class="highlight-list">
            <div
              v-for="item in highlightList"
              :key="item.label"
              class="highlight-item"
            >
              <p class="highlight-label">{{ item.label }}</p>
              <p class="highlight-value">{{ item.value }}</p>
            </div>
          </div>
        </el-card>

        <el-card shadow="never" class="insight-card tips-card">
          <template #header>
            <div class="card-header">
              <el-icon class="card-icon"><InfoFilled /></el-icon>
              <span class="card-title">操作提示</span>
            </div>
          </template>
          <el-alert
            class="tips-alert"
            :title="nextActionText"
            :type="completionPercent === 100 ? 'success' : 'warning'"
            show-icon
            :closable="false"
          />
          <ul class="tips-list">
            <li v-for="tip in insightTips" :key="tip">
              <span class="tips-dot" />
              <span>{{ tip }}</span>
            </li>
          </ul>
        </el-card>
      </div>
    </div>
    <el-dialog
      v-model="inspectionDialogVisible"
      title="选择出货检验单"
      width="960px"
      class="inspection-dialog"
      :close-on-click-modal="false"
    >
      <div class="inspection-search">
        <el-input
          v-model="inspectionSearchForm.keyword"
          placeholder="请输入出货检验单编号/名称"
          clearable
        />
        <el-input
          v-model="inspectionSearchForm.productKeyword"
          placeholder="请输入产品编号/名称"
          clearable
        />
        <el-date-picker
          v-model="inspectionSearchForm.inspectionDate"
          type="date"
          placeholder="请选择检验日期"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          style="width: 100%"
        />
        <div class="inspection-search__actions">
          <el-button @click="handleInspectionReset">重置</el-button>
          <el-button
            type="primary"
            :loading="inspectionLoading"
            @click="handleInspectionSearch"
          >
            查询
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="inspectionLoading"
        :data="inspectionTableData"
        border
        stripe
        highlight-current-row
        class="inspection-table"
        @row-dblclick="handleInspectionRowDblClick"
      >
        <el-table-column label="选择" width="70" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedInspectionId"
              :label="row.id"
              @change="() => handleInspectionRowSelect(row)"
            />
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column
          prop="inspectionName"
          label="检验单名称"
          min-width="160"
        />
        <el-table-column
          prop="inspectionCode"
          label="检验单号"
          min-width="140"
        />
        <el-table-column prop="productName" label="产品信息" min-width="160">
          <template #default="{ row }">
            <div class="inspection-product-cell">
              <span>{{ row.productName || "-" }}</span>
              <span class="product-code">{{ row.productCode || "" }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="specification"
          label="规格型号"
          min-width="120"
        />
        <el-table-column prop="unit" label="单位" width="70" align="center" />
        <el-table-column prop="batchNo" label="批次号" min-width="130" />
        <el-table-column
          prop="inspectionDate"
          label="检验日期"
          min-width="130"
          :formatter="formatInspectionDate"
        />
      </el-table>

      <div class="inspection-pagination">
        <el-pagination
          v-model:current-page="inspectionPagination.pageIndex"
          v-model:page-size="inspectionPagination.pageSize"
          :total="inspectionPagination.total"
          layout="prev, pager, next, sizes"
          :page-sizes="[10, 20, 30, 50]"
          @current-change="handleInspectionPageChange"
          @size-change="handleInspectionSizeChange"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="inspectionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleInspectionConfirm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="customerDialogVisible"
      title="选择客户"
      width="900px"
      class="customer-dialog"
      :close-on-click-modal="false"
    >
      <div class="customer-search">
        <el-input
          v-model="customerSearchForm.keyword"
          placeholder="请输入客户名称/编号/联系人"
          clearable
          @keyup.enter="handleCustomerSearch"
        />
        <div class="customer-search__actions">
          <el-button @click="handleCustomerReset">重置</el-button>
          <el-button
            type="primary"
            :loading="customerLoading"
            @click="handleCustomerSearch"
            >查询</el-button
          >
        </div>
      </div>
      <el-table
        v-loading="customerLoading"
        :data="customerTableData"
        border
        stripe
        highlight-current-row
        class="customer-table"
        @row-dblclick="handleCustomerRowDblClick"
      >
        <el-table-column label="选择" width="70" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedCustomerId"
              :label="row.id"
              @change="() => handleCustomerRowSelect(row)"
            />
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="name" label="客户名称" min-width="180" />
        <el-table-column prop="code" label="客户编号" min-width="150" />
        <el-table-column prop="type" label="客户类型" width="120" />
        <el-table-column prop="contact" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" min-width="150" />
      </el-table>
      <div class="customer-pagination">
        <el-pagination
          v-model:current-page="customerPagination.pageIndex"
          v-model:page-size="customerPagination.pageSize"
          :total="customerPagination.totalCount"
          layout="prev, pager, next, sizes"
          :page-sizes="[10, 20, 30, 50]"
          @current-change="handleCustomerPageChange"
          @size-change="handleCustomerSizeChange"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="customerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCustomerConfirm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="batchDialogVisible"
      title="选择批次号"
      width="820px"
      class="batch-dialog"
      :close-on-click-modal="false"
    >
      <div class="batch-dialog-toolbar">
        <el-input
          v-model="batchSearchCode"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleBatchSearch"
        />
        <div class="batch-dialog-toolbar__actions">
          <el-button @click="handleBatchReset">重置</el-button>
          <el-button
            type="primary"
            :loading="batchListLoading"
            @click="handleBatchSearch"
            >查询</el-button
          >
        </div>
      </div>
      <el-table
        v-loading="batchListLoading"
        :data="batchTableData"
        border
        stripe
        highlight-current-row
        class="batch-dialog-table"
        @row-dblclick="handleBatchRowDblClick"
      >
        <el-table-column label="选择" width="70" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedBatchId"
              :label="row.id"
              @change="() => handleBatchRowSelect(row)"
            />
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="batchCode" label="批次号" min-width="160" />
        <el-table-column prop="createTime" label="生产日期" min-width="150">
          <template #default="{ row }">
            {{ formatBatchDate(row.createTime) || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="到期日期" min-width="150">
          <template #default="{ row }">
            {{ formatBatchDate(row.endTime) || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="inventory" label="库存数量" min-width="120" />
      </el-table>
      <div class="batch-dialog-pagination">
        <el-pagination
          v-model:current-page="batchPagination.pageIndex"
          v-model:page-size="batchPagination.pageSize"
          :total="batchPagination.total"
          layout="prev, pager, next, sizes"
          :page-sizes="[10, 20, 30, 50]"
          @current-change="handleBatchPageChange"
          @size-change="handleBatchSizeChange"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      v-model="warehouseDialogVisible"
      title="选择仓库"
      width="920px"
      class="warehouse-dialog"
      :close-on-click-modal="false"
    >
      <div class="warehouse-summary">
        <span>仓库名称：{{ selectedWarehouseOption?.name || "未选择" }}</span>
        <span>库区名称：{{ selectedReservoirOption?.name || "未选择" }}</span>
        <span>库位名称：{{ selectedSeatOption?.name || "未选择" }}</span>
      </div>
      <div class="warehouse-selector">
        <div class="selector-column">
          <div class="selector-column__header">
            <span class="selector-column__title">仓库名称</span>
            <el-input
              v-model="warehouseSearchForm.warehouse"
              placeholder="请输入"
              clearable
              @keyup.enter="handleWarehouseSearchSubmit('warehouse')"
              @clear="handleWarehouseSearchSubmit('warehouse')"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <el-scrollbar
            class="selector-column__list"
            v-loading="warehouseListLoading"
          >
            <div
              v-for="option in warehouseOptions"
              :key="option.id"
              :class="[
                'selector-item',
                { active: option.id === selectedWarehouseId },
              ]"
              @click="selectWarehouseOption(option)"
            >
              {{ option.name }}
            </div>
          </el-scrollbar>
        </div>
        <div class="selector-column">
          <div class="selector-column__header">
            <span class="selector-column__title">库区名称</span>
            <el-input
              v-model="warehouseSearchForm.reservoir"
              placeholder="请输入"
              clearable
              :disabled="!selectedWarehouseId"
              @keyup.enter="handleWarehouseSearchSubmit('reservoir')"
              @clear="handleWarehouseSearchSubmit('reservoir')"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <el-scrollbar
            class="selector-column__list"
            v-loading="reservoirListLoading"
          >
            <div
              v-for="option in reservoirOptions"
              :key="option.id"
              :class="[
                'selector-item',
                { active: option.id === selectedReservoirId },
              ]"
              @click="selectReservoirOption(option)"
            >
              {{ option.name }}
            </div>
            <el-empty
              v-if="!reservoirListLoading && !reservoirOptions.length"
              description="请先选择仓库"
            />
          </el-scrollbar>
        </div>
        <div class="selector-column">
          <div class="selector-column__header">
            <span class="selector-column__title">库位名称</span>
            <el-input
              v-model="warehouseSearchForm.seat"
              placeholder="请输入"
              clearable
              :disabled="!selectedReservoirId"
              @keyup.enter="handleWarehouseSearchSubmit('seat')"
              @clear="handleWarehouseSearchSubmit('seat')"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <el-scrollbar
            class="selector-column__list"
            v-loading="seatListLoading"
          >
            <div
              v-for="option in seatOptions"
              :key="option.id"
              :class="[
                'selector-item',
                { active: option.id === selectedSeatId },
              ]"
              @click="selectSeatOption(option)"
            >
              {{ option.name }}
            </div>
            <el-empty
              v-if="
                !seatListLoading &&
                (!selectedReservoirId || !seatOptions.length)
              "
              :description="
                selectedReservoirId
                  ? '暂无库位，请更换搜索条件'
                  : '请先选择库区'
              "
            />
          </el-scrollbar>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warehouseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleWarehouseConfirm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  ArrowRight,
  Box,
  Calendar,
  CircleCheckFilled,
  Document,
  DocumentCopy,
  InfoFilled,
  List,
  Search,
  Timer,
  User,
  WarningFilled,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import https from "@/Http/http";
import moment from "moment";

interface SalesOutboundDetail {
  id?: number;
  productName: string;
  productNo: string;
  specification?: string;
  unit?: string;
  productionDate?: string;
  expiryDate?: string;
  batchNo?: string;
  batch?: string;
  batchNoId?: number;
  outboundQuantity?: number;
  warehouseName?: string;
  warehouseId?: string | null;
  warehouseManager?: string;
}

interface WarehouseOption {
  id: number;
  name: string;
  principal?: string;
}

interface ReservoirOption {
  id: number;
  name: string;
  warehouseId?: number;
}

interface SeatOption {
  id: number;
  name: string;
  warehouseId?: number;
  reservoirId?: number;
}

interface BatchItem {
  id: number;
  batchCode: string;
  createTime?: string | null;
  endTime?: string | null;
  inventory?: number | null;
}

interface CustomerRow {
  id: number;
  code: string;
  name: string;
  type?: string;
  contact?: string;
  phone?: string;
}

interface ProductInspectionItem {
  id: number;
  inspectionCode: string;
  inspectionName?: string;
  productName?: string;
  productCode?: string;
  specification?: string;
  unit?: string;
  batchNo?: string;
  inspectionDate?: string;
}

interface SalesOutboundForm {
  id?: number;
  outboundNo: string;
  outboundName: string;
  inspectionOrderId?: number;
  inspectionOrderNo?: string;
  inspectionOrderName?: string;
  outboundDate?: string;
  salesOrderNo?: string;
  machineName?: string;
  customerId?: number;
  customerName?: string;
  totalQuantity?: number;
  remark?: string;
  systemGenerated: boolean;
  details: SalesOutboundDetail[];
}

const route = useRoute();
const router = useRouter();
const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const pageLoading = ref(true);

const isEdit = computed(
  () => route.query.mode === "edit" && !!route.query.editId
);

const createDefaultDetail = (): SalesOutboundDetail => ({
  productName: "",
  productNo: "",
  specification: "",
  unit: "",
  productionDate: "",
  expiryDate: "",
  batchNo: "",
  batch: "",
  batchNoId: undefined,
  outboundQuantity: undefined,
  warehouseName: "",
  warehouseId: "",
  warehouseManager: "",
});

const formData = reactive<SalesOutboundForm>({
  outboundNo: "",
  outboundName: "",
  inspectionOrderNo: "",
  inspectionOrderName: "",
  salesOrderNo: "",
  customerName: "",
  systemGenerated: true,
  details: [createDefaultDetail()],
});

const inspectionDialogVisible = ref(false);
const inspectionLoading = ref(false);
const inspectionTableData = ref<ProductInspectionItem[]>([]);
const inspectionPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});
const inspectionSearchForm = reactive({
  keyword: "",
  productKeyword: "",
  inspectionDate: null as string | null,
});
const selectedInspectionId = ref<number | null>(null);
const selectedInspection = ref<ProductInspectionItem | null>(null);

const customerDialogVisible = ref(false);
const customerLoading = ref(false);
const customerTableData = ref<CustomerRow[]>([]);
const selectedCustomerId = ref<number | null>(null);
const selectedCustomer = ref<CustomerRow | null>(null);
const customerSearchForm = reactive({
  keyword: "",
});
const customerPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
});

const batchDialogVisible = ref(false);
const batchListLoading = ref(false);
const batchTableData = ref<BatchItem[]>([]);
const batchSearchCode = ref("");
const batchPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});
const selectedBatchId = ref<number | null>(null);
const selectedBatchRow = ref<BatchItem | null>(null);
const currentBatchDetailIndex = ref<number | null>(null);

const warehouseDialogVisible = ref(false);
const currentWarehouseDetailIndex = ref<number | null>(null);
const warehouseOptions = ref<WarehouseOption[]>([]);
const reservoirOptions = ref<ReservoirOption[]>([]);
const seatOptions = ref<SeatOption[]>([]);
const warehouseListLoading = ref(false);
const reservoirListLoading = ref(false);
const seatListLoading = ref(false);
const warehouseSearchForm = reactive({
  warehouse: "",
  reservoir: "",
  seat: "",
});
const selectedWarehouseId = ref<number | null>(null);
const selectedReservoirId = ref<number | null>(null);
const selectedSeatId = ref<number | null>(null);
const selectedWarehouseOption = ref<WarehouseOption | null>(null);
const selectedReservoirOption = ref<ReservoirOption | null>(null);
const selectedSeatOption = ref<SeatOption | null>(null);

const formRules: FormRules = {
  outboundNo: [
    { required: true, message: "请输入出库单编号", trigger: "blur" },
  ],
  outboundName: [
    { required: true, message: "请输入出库单名称", trigger: "blur" },
  ],
  outboundDate: [
    { required: true, message: "请选择出库日期", trigger: "change" },
  ],
  salesOrderNo: [
    { required: true, message: "请输入销售单号", trigger: "blur" },
  ],
};

const currentStep = computed(() => {
  let step = 1;
  if (formData.customerName) {
    step = 2;
  }
  const detail = formData.details?.[0];
  if (detail?.warehouseName && detail?.outboundQuantity) {
    step = 3;
  }
  return step;
});

const primaryDetail = computed(
  () => formData.details?.[0] || ({} as SalesOutboundDetail)
);

const checklistSteps = computed(() => {
  const baseFilled =
    !!formData.outboundNo && !!formData.outboundName && !!formData.outboundDate;
  const relationFilled =
    !!formData.customerName && !!formData.inspectionOrderNo;
  const detailFilled =
    !!primaryDetail.value?.productName &&
    !!primaryDetail.value?.outboundQuantity &&
    !!primaryDetail.value?.warehouseName;

  return [
    {
      label: "基础信息",
      description: "编号、名称、日期及备注",
      complete: baseFilled,
    },
    {
      label: "客户与检验",
      description: "客户档案与检验单",
      complete: relationFilled,
    },
    {
      label: "出库明细",
      description: "产品、数量及仓储信息",
      complete: detailFilled,
    },
  ];
});

const completionPercent = computed(() => {
  const total = checklistSteps.value.length || 1;
  const done = checklistSteps.value.filter((item) => item.complete).length;
  return Math.round((done / total) * 100);
});

const progressColor = computed(() =>
  completionPercent.value === 100 ? "#34d399" : "#409eff"
);

const nextActionText = computed(() => {
  const next = checklistSteps.value.find((item) => !item.complete);
  return next ? `下一步：${next.label}` : "所有步骤已完成，随时可以提交";
});

const highlightList = computed(() => {
  const formatValue = (value: string | number | undefined | null) => {
    if (value === undefined || value === null || value === "") {
      return "未填写";
    }
    return value;
  };

  return [
    { label: "出库产品", value: formatValue(primaryDetail.value?.productName) },
    { label: "产品编号", value: formatValue(primaryDetail.value?.productNo) },
    {
      label: "目标仓库",
      value: formatValue(primaryDetail.value?.warehouseName),
    },
    {
      label: "计划数量",
      value: formatValue(formData.totalQuantity ?? 0),
    },
    { label: "客户", value: formatValue(formData.customerName) },
    {
      label: "出库日期",
      value: formatValue(formatDisplayDate(formData.outboundDate)),
    },
  ];
});

const insightTips = computed(() => {
  const tips: string[] = [];
  if (!formData.customerName) {
    tips.push("请选择客户以便自动填充往来信息。");
  }
  if (!formData.inspectionOrderNo) {
    tips.push("关联出货检验单能减少手工录入风险。");
  }
  if (!primaryDetail.value?.warehouseName) {
    tips.push("请选择仓库/库区/库位，确保库存定位准确。");
  }
  if (!primaryDetail.value?.outboundQuantity) {
    tips.push("录入出库数量后系统会自动汇总总量。");
  }
  if (!tips.length) {
    tips.push("关键信息完整，可直接提交或再次复核。");
  }
  return tips;
});

const formatDisplayDate = (date?: string | null) => {
  if (!date) {
    return "待选择";
  }
  return moment(date).format("YYYY-MM-DD");
};

// 初始化表单数据
const initFormData = async () => {
  try {
    if (isEdit.value && route.query.editData) {
      const editData = JSON.parse(
        decodeURIComponent(route.query.editData as string)
      );

      // 清空现有数据
      Object.keys(formData).forEach((key) => {
        if (key === "details") {
          formData.details.splice(
            0,
            formData.details.length,
            createDefaultDetail()
          );
        } else if (key !== "systemGenerated") {
          (formData as any)[key] = "";
        }
      });

      // 赋值编辑数据
      Object.assign(formData, {
        ...editData,
        inspectionOrderName:
          editData.inspectionOrderName ?? editData.inspectionOrderNo ?? "",
        systemGenerated: false, // 编辑模式不使用系统生成
        details: [],
      });

      const firstDetail = Array.isArray(editData.details)
        ? editData.details[0]
        : null;
      const normalizedDetail = firstDetail
        ? { ...createDefaultDetail(), ...firstDetail }
        : createDefaultDetail();
      if (
        normalizedDetail.batch === undefined ||
        normalizedDetail.batch === null ||
        normalizedDetail.batch === ""
      ) {
        normalizedDetail.batch = normalizedDetail.batchNo || "";
      }
      if (!normalizedDetail.batchNo && normalizedDetail.batch) {
        normalizedDetail.batchNo = normalizedDetail.batch;
      }
      if (
        normalizedDetail.warehouseId !== undefined &&
        normalizedDetail.warehouseId !== null &&
        normalizedDetail.warehouseId !== ""
      ) {
        normalizedDetail.warehouseId = String(normalizedDetail.warehouseId);
      }
      formData.details.splice(0, formData.details.length, normalizedDetail);
      formData.totalQuantity = normalizedDetail.outboundQuantity || 0;

      console.log("编辑数据加载成功:", formData);
    } else {
      // 新增时设置默认值
      formData.outboundDate = moment().format("YYYY-MM-DD");
      formData.systemGenerated = true;
      generateOutboundNo();

      // 仅保留一条明细
      formData.details.splice(
        0,
        formData.details.length,
        createDefaultDetail()
      );
      formData.totalQuantity = 0;

      console.log("新增模式初始化完成:", formData);
    }
  } catch (error) {
    console.error("初始化表单数据失败:", error);
    ElMessage.error("数据解析失败，请重新尝试");
    router.push("/SalesOutboundList");
  }
};

// 生成出库单编号
const generateOutboundNo = () => {
  if (formData.systemGenerated) {
    const timestamp = moment().format("YYYYMMDDHHmmss");
    formData.outboundNo = `SO${timestamp}`;
  }
};

// 系统编号切换
const handleSystemGeneratedChange = (value: boolean) => {
  if (value) {
    generateOutboundNo();
  } else {
    formData.outboundNo = "";
  }
};

const handleCopyOutboundNo = async () => {
  if (!formData.outboundNo) {
    ElMessage.warning("暂无可复制的编号");
    return;
  }
  try {
    if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(formData.outboundNo);
    } else {
      const textarea = document.createElement("textarea");
      textarea.value = formData.outboundNo;
      textarea.style.position = "fixed";
      textarea.style.opacity = "0";
      document.body.appendChild(textarea);
      textarea.focus();
      textarea.select();
      document.execCommand("copy");
      document.body.removeChild(textarea);
    }
    ElMessage.success("编号已复制");
  } catch (error) {
    console.error("复制出库单编号失败:", error);
    ElMessage.error("复制失败，请手动选择文本复制");
  }
};

// 选择出货检验单
const handleSelectInspection = () => {
  inspectionDialogVisible.value = true;
  selectedInspectionId.value = formData.inspectionOrderId || null;
  selectedInspection.value = formData.inspectionOrderId
    ? ({
        id: formData.inspectionOrderId,
        inspectionCode: formData.inspectionOrderNo || "",
        inspectionName: formData.inspectionOrderName || "",
      } as ProductInspectionItem)
    : null;
  if (!inspectionTableData.value.length) {
    loadInspectionList();
  }
};

// 选择客户
const handleSelectCustomer = () => {
  customerDialogVisible.value = true;
  customerPagination.pageIndex = 1;
  selectedCustomerId.value = formData.customerId ?? null;
  selectedCustomer.value = null;
  fetchCustomerList();
};

const mapCustomerRow = (row: any): CustomerRow => ({
  id: Number(
    row.id ??
      row.ID ??
      row.customerId ??
      row.CustomerId ??
      row.CustId ??
      row.custId ??
      0
  ),
  code:
    row.custnumber ??
    row.custNumber ??
    row.customerCode ??
    row.customer_code ??
    row.code ??
    "",
  name:
    row.custname ??
    row.custName ??
    row.customerName ??
    row.customer_name ??
    row.name ??
    "",
  type: row.custtype ?? row.custType ?? row.customerType ?? row.type ?? "",
  contact:
    row.people ?? row.People ?? row.contact ?? row.linkman ?? row.Contact ?? "",
  phone: row.phone ?? row.tel ?? row.mobile ?? row.telephone ?? row.Phone ?? "",
});

const buildCustomerQueryParams = () => {
  const params: Record<string, any> = {
    pageindex: customerPagination.pageIndex,
    pagesize: customerPagination.pageSize,
  };
  if (customerSearchForm.keyword?.trim()) {
    params.name = customerSearchForm.keyword.trim();
  }
  return params;
};

const fetchCustomerList = async () => {
  customerLoading.value = true;
  try {
    const res = await https.Reads.get("/Cust/ShowCust", {
      params: buildCustomerQueryParams(),
    });
    const responseData = res?.data ?? {};
    const code = responseData.code ?? responseData.Code ?? 0;
    if (code !== 1) {
      const msg = responseData.msg ?? responseData.Msg ?? "获取客户列表失败";
      throw new Error(msg);
    }
    const rawList = Array.isArray(responseData.data)
      ? responseData.data
      : Array.isArray(responseData.Data)
      ? responseData.Data
      : [];
    customerTableData.value = rawList.map(mapCustomerRow);
    customerPagination.totalCount =
      responseData.totalCount ??
      responseData.TotalCount ??
      customerTableData.value.length;
  } catch (error: any) {
    console.error("获取客户列表失败:", error);
    customerTableData.value = [];
    customerPagination.totalCount = 0;
    ElMessage.error(error?.message || "获取客户列表失败，请稍后重试");
  } finally {
    customerLoading.value = false;
  }
};

const handleCustomerSearch = () => {
  customerPagination.pageIndex = 1;
  fetchCustomerList();
};

const handleCustomerReset = () => {
  customerSearchForm.keyword = "";
  handleCustomerSearch();
};

const handleCustomerPageChange = (page: number) => {
  customerPagination.pageIndex = page;
  fetchCustomerList();
};

const handleCustomerSizeChange = (size: number) => {
  customerPagination.pageSize = size;
  customerPagination.pageIndex = 1;
  fetchCustomerList();
};

const handleCustomerRowSelect = (row: CustomerRow) => {
  selectedCustomerId.value = row.id;
  selectedCustomer.value = row;
};

const handleCustomerRowDblClick = (row: CustomerRow) => {
  handleCustomerRowSelect(row);
  handleCustomerConfirm();
};

const handleCustomerConfirm = () => {
  const target =
    selectedCustomer.value ||
    customerTableData.value.find(
      (item) => item.id === selectedCustomerId.value
    ) ||
    null;
  if (!target) {
    ElMessage.warning("请选择客户");
    return;
  }
  formData.customerId = target.id;
  formData.customerName = target.name;
  customerDialogVisible.value = false;
};

const formatBatchDate = (value?: string | null) => {
  if (!value) return null;
  const formatted = moment(value).isValid()
    ? moment(value).format("YYYY-MM-DD")
    : value.split("T")[0] || null;
  return formatted;
};

const normalizeBatchItem = (item: any): BatchItem => ({
  id: Number(item.id ?? item.Id ?? 0),
  batchCode: item.batchCode ?? item.BatchCode ?? "",
  createTime: item.createTime ?? item.CreateTime ?? null,
  endTime: item.endTime ?? item.EndTime ?? null,
  inventory: item.inventory ?? item.Inventory ?? null,
});

const normalizeWarehouseOption = (item: any): WarehouseOption => ({
  id: Number(item.id ?? item.Id ?? 0),
  name:
    item.warehousenmae ??
    item.warehousename ??
    item.warehouseName ??
    item.Warehousenmae ??
    item.name ??
    "",
  principal:
    item.principal ??
    item.Principal ??
    item.warehousePrincipal ??
    item.WarehousePrincipal ??
    "",
});

const normalizeReservoirOption = (item: any): ReservoirOption => ({
  id: Number(item.id ?? item.Id ?? 0),
  name:
    item.reservoirnmae ??
    item.reservoirname ??
    item.Reservoirnmae ??
    item.name ??
    "",
  warehouseId: item.warehouseid ?? item.Warehouseid ?? item.warehouseId,
});

const normalizeSeatOption = (item: any): SeatOption => ({
  id: Number(item.id ?? item.Id ?? 0),
  name: item.seatnmae ?? item.seatname ?? item.Seatnmae ?? item.name ?? "",
  warehouseId: item.warehouseid ?? item.Warehouseid ?? item.warehouseId,
  reservoirId: item.reservoirid ?? item.Reservoirid ?? item.reservoirId,
});

const fetchBatchList = async () => {
  batchListLoading.value = true;
  try {
    const params: Record<string, any> = {
      PageIndex: batchPagination.pageIndex,
      PageSize: batchPagination.pageSize,
    };
    if (batchSearchCode.value.trim()) {
      params.BatchCode = batchSearchCode.value.trim();
    }
    const res = await https.Reads.get("/Warehouse/BatchList", { params });
    const payload = res?.data ?? {};
    const rawList = Array.isArray(payload.data)
      ? payload.data
      : Array.isArray(payload.Data)
      ? payload.Data
      : [];
    batchTableData.value = rawList.map(normalizeBatchItem);
    batchPagination.total =
      payload.totalCount ?? payload.TotalCount ?? batchTableData.value.length;
  } catch (error: any) {
    console.error("获取批次列表失败:", error);
    ElMessage.error(error?.message || "获取批次列表失败，请稍后重试");
    batchTableData.value = [];
    batchPagination.total = 0;
  } finally {
    batchListLoading.value = false;
  }
};

const handleSelectBatch = (detailIndex: number) => {
  currentBatchDetailIndex.value = detailIndex;
  selectedBatchId.value = formData.details[detailIndex]?.batchNoId ?? null;
  selectedBatchRow.value = null;
  batchDialogVisible.value = true;
  batchPagination.pageIndex = 1;
  fetchBatchList();
};

const handleBatchSearch = () => {
  batchPagination.pageIndex = 1;
  fetchBatchList();
};

const handleBatchReset = () => {
  batchSearchCode.value = "";
  handleBatchSearch();
};

const handleBatchPageChange = (page: number) => {
  batchPagination.pageIndex = page;
  fetchBatchList();
};

const handleBatchSizeChange = (size: number) => {
  batchPagination.pageSize = size;
  batchPagination.pageIndex = 1;
  fetchBatchList();
};

const handleBatchRowSelect = (row: BatchItem) => {
  selectedBatchId.value = row.id;
  selectedBatchRow.value = row;
};

const handleBatchRowDblClick = (row: BatchItem) => {
  handleBatchRowSelect(row);
  handleBatchConfirm();
};

const ensureDetailAtIndex = (index: number): SalesOutboundDetail => {
  while (formData.details.length <= index) {
    formData.details.push(createDefaultDetail());
  }
  return formData.details[index]!;
};

// 选择仓库
const handleSelectWarehouse = (detailIndex: number) => {
  currentWarehouseDetailIndex.value = detailIndex;
  warehouseDialogVisible.value = true;
  resetWarehouseDialogState();
  fetchWarehouseOptions();
};

const handleWarehouseSearchSubmit = (
  type: "warehouse" | "reservoir" | "seat"
) => {
  if (type === "warehouse") {
    fetchWarehouseOptions();
  } else if (type === "reservoir") {
    if (!selectedWarehouseId.value) {
      ElMessage.warning("请先选择仓库");
      return;
    }
    fetchReservoirOptions();
  } else {
    if (!selectedReservoirId.value) {
      ElMessage.warning("请先选择库区");
      return;
    }
    fetchSeatOptions();
  }
};

const selectWarehouseOption = (option: WarehouseOption) => {
  selectedWarehouseId.value = option.id;
  selectedWarehouseOption.value = option;
  selectedReservoirId.value = null;
  selectedSeatId.value = null;
  selectedReservoirOption.value = null;
  selectedSeatOption.value = null;
  fetchReservoirOptions();
  seatOptions.value = [];
};

const selectReservoirOption = (option: ReservoirOption) => {
  selectedReservoirId.value = option.id;
  selectedReservoirOption.value = option;
  selectedSeatId.value = null;
  selectedSeatOption.value = null;
  fetchSeatOptions();
};

const selectSeatOption = (option: SeatOption) => {
  selectedSeatId.value = option.id;
  selectedSeatOption.value = option;
};

const handleWarehouseConfirm = () => {
  if (
    currentWarehouseDetailIndex.value === null ||
    !selectedWarehouseOption.value ||
    !selectedReservoirOption.value ||
    !selectedSeatOption.value
  ) {
    ElMessage.warning("请完整选择仓库、库区和库位");
    return;
  }
  const detail = ensureDetailAtIndex(currentWarehouseDetailIndex.value);
  const warehouseNameParts = [
    selectedWarehouseOption.value.name,
    selectedReservoirOption.value.name,
    selectedSeatOption.value.name,
  ].filter(Boolean);
  detail.warehouseName = warehouseNameParts.join(" / ");
  detail.warehouseManager = selectedWarehouseOption.value.principal || "";
  detail.warehouseId = String(selectedWarehouseOption.value.id);
  warehouseDialogVisible.value = false;
};

// 数量变化时重新计算总数量
const handleQuantityChange = () => {
  calculateTotalQuantity();
};

// 计算总数量
const calculateTotalQuantity = () => {
  const total = formData.details.reduce((sum, detail) => {
    return sum + (detail.outboundQuantity || 0);
  }, 0);
  formData.totalQuantity = total;
};

// 验证明细字段
const validateDetailField = (
  index: number,
  field: keyof SalesOutboundDetail
) => {
  const detail = formData.details[index];
  if (!detail) return;

  const value = detail[field];
  const isEmpty =
    value === undefined ||
    value === null ||
    (typeof value === "string" && value.trim() === "") ||
    (typeof value === "number" && value <= 0);

  if (isEmpty) {
    ElMessage.warning(`第 ${index + 1} 行的${getFieldLabel(field)}不能为空`);
  }
};

// 获取字段标签
const getFieldLabel = (field: keyof SalesOutboundDetail): string => {
  const labels: Record<string, string> = {
    productName: "产品名称",
    productNo: "产品编号",
    outboundQuantity: "出库数量",
  };
  return labels[field] || field;
};

// 验证明细数据
const validateDetails = (): boolean => {
  if (!formData.details.length) {
    ElMessage.error("请至少添加一条出库明细");
    return false;
  }

  for (let i = 0; i < formData.details.length; i++) {
    const detail = formData.details[i];
    if (!detail) {
      continue;
    }
    if (!detail.productName) {
      ElMessage.error(`第 ${i + 1} 行的产品名称不能为空`);
      return false;
    }
    if (!detail.productNo) {
      ElMessage.error(`第 ${i + 1} 行的产品编号不能为空`);
      return false;
    }
    if (!detail.outboundQuantity || detail.outboundQuantity <= 0) {
      ElMessage.error(`第 ${i + 1} 行的出库数量必须大于0`);
      return false;
    }
  }
  return true;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    // 验证基本信息
    await formRef.value.validate();

    // 验证明细信息
    if (!validateDetails()) {
      return;
    }

    submitLoading.value = true;

    // 构建提交数据
    const submitData = {
      id: isEdit.value ? formData.id : undefined,
      outboundNo: formData.outboundNo,
      outboundName: formData.outboundName,
      inspectionOrderId: formData.inspectionOrderId || null,
      inspectionOrderNo: formData.inspectionOrderNo || "",
      outboundDate: formData.outboundDate,
      salesOrderNo: formData.salesOrderNo,
      machineName: formData.machineName || formData.customerName || "",
      customerId: formData.customerId || null,
      remark: formData.remark || "",
      stats: 0, // 新增时默认为待出库状态
      detail: formData.details.map((detail) => ({
        id: isEdit.value ? detail.id : undefined,
        productName: detail.productName,
        productNo: detail.productNo,
        specification: detail.specification || "",
        unit: detail.unit || "",
        productionDate: detail.productionDate || null,
        expiryDate: detail.expiryDate || null,
        batchNoId: detail.batchNoId || null,
        batch: detail.batch || detail.batchNo || "",
        outboundQuantity: detail.outboundQuantity || 0,
        warehouseName: (detail.warehouseName || "").trim(),
        warehouseManager: detail.warehouseManager || "",
      })),
    };

    console.log("提交数据:", submitData);

    const apiUrl = isEdit.value
      ? "/Warehouse/SalesOutboundUpdate"
      : "/Warehouse/SalesOutboundAdd";

    const response = await https.Writes[isEdit.value ? "put" : "post"](
      apiUrl,
      submitData
    );

    const responseData = response?.data ?? {};
    const code = responseData.code ?? responseData.Code;

    if (code === 1) {
      const successMsg =
        responseData.msg ??
        responseData.Msg ??
        `销售出库${isEdit.value ? "编辑" : "新增"}成功`;

      ElMessage.success(successMsg);

      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        router.push("/SalesOutboundList");
      }, 1000);
    } else {
      const errorMsg =
        responseData.msg ??
        responseData.Msg ??
        `销售出库${isEdit.value ? "编辑" : "新增"}失败`;
      throw new Error(errorMsg);
    }
  } catch (error: any) {
    console.error(`${isEdit.value ? "编辑" : "新增"}销售出库失败:`, error);

    let errorMsg = `销售出库${isEdit.value ? "编辑" : "新增"}失败，请稍后重试`;

    if (error?.response?.status === 400) {
      errorMsg = "请求参数错误，请检查输入数据";
    } else if (error?.response?.status === 401) {
      errorMsg = "登录已过期，请重新登录";
    } else if (error?.response?.status === 403) {
      errorMsg = "权限不足，无法执行此操作";
    } else if (error?.response?.status === 500) {
      errorMsg = "服务器内部错误，请联系管理员";
    } else if (error?.message) {
      errorMsg = error.message;
    }

    ElMessage.error(errorMsg);
  } finally {
    submitLoading.value = false;
  }
};

const buildInspectionQueryParams = () => {
  const params: Record<string, any> = {
    pageindex: inspectionPagination.pageIndex,
    pagesize: inspectionPagination.pageSize,
  };
  if (inspectionSearchForm.keyword?.trim()) {
    params.keyword = inspectionSearchForm.keyword.trim();
  }
  if (inspectionSearchForm.productKeyword?.trim()) {
    params.productkeyword = inspectionSearchForm.productKeyword.trim();
  }
  if (inspectionSearchForm.inspectionDate) {
    params.inspectiondate = inspectionSearchForm.inspectionDate;
  }
  return params;
};

const mapInspectionItem = (item: any): ProductInspectionItem => ({
  id: item.id ?? item.Id ?? 0,
  inspectionCode:
    item.inspectioncode ?? item.Inspectioncode ?? item.inspectionCode ?? "",
  inspectionName:
    item.inspectionname ?? item.Inspectionname ?? item.inspectionName ?? "",
  productName:
    item.productname ??
    item.productName ??
    item.ProductName ??
    item.Productname ??
    "",
  productCode:
    item.productcode ??
    item.productCode ??
    item.ProductCode ??
    item.Productcode ??
    "",
  specification: item.specification ?? item.Specification ?? "",
  unit: item.unit ?? item.Unit ?? "",
  batchNo: item.batchno ?? item.batchNo ?? item.Batchno ?? item.BatchNo ?? "",
  inspectionDate:
    item.inspectiondate ??
    item.inspectionDate ??
    item.Inspectiondate ??
    item.InspectionDate ??
    "",
});

const loadInspectionList = async () => {
  inspectionLoading.value = true;
  try {
    const res = await https.Reads.get("/ProductInspection/List", {
      params: buildInspectionQueryParams(),
    });
    const responseData = res?.data ?? {};
    const code = responseData.code ?? responseData.Code ?? 0;
    if (code !== 1) {
      const msg = responseData.msg ?? responseData.Msg ?? "获取出货检验单失败";
      throw new Error(msg);
    }
    const rawList = Array.isArray(responseData.data)
      ? responseData.data
      : Array.isArray(responseData.Data)
      ? responseData.Data
      : [];
    inspectionTableData.value = rawList.map(mapInspectionItem);
    inspectionPagination.total =
      responseData.totalCount ??
      responseData.TotalCount ??
      inspectionTableData.value.length;
  } catch (error: any) {
    console.error("加载出货检验单失败:", error);
    ElMessage.error(error?.message || "获取出货检验单失败");
  } finally {
    inspectionLoading.value = false;
  }
};

const handleInspectionSearch = () => {
  inspectionPagination.pageIndex = 1;
  loadInspectionList();
};

const handleInspectionReset = () => {
  inspectionSearchForm.keyword = "";
  inspectionSearchForm.productKeyword = "";
  inspectionSearchForm.inspectionDate = null;
  inspectionPagination.pageIndex = 1;
  loadInspectionList();
};

const handleInspectionPageChange = (page: number) => {
  inspectionPagination.pageIndex = page;
  loadInspectionList();
};

const handleInspectionSizeChange = (size: number) => {
  inspectionPagination.pageSize = size;
  inspectionPagination.pageIndex = 1;
  loadInspectionList();
};

const handleInspectionRowSelect = (row: ProductInspectionItem) => {
  selectedInspectionId.value = row.id;
  selectedInspection.value = row;
};

const handleInspectionRowDblClick = (row: ProductInspectionItem) => {
  handleInspectionRowSelect(row);
  handleInspectionConfirm();
};

const ensureFirstDetail = (): SalesOutboundDetail => ensureDetailAtIndex(0);

const applyInspectionProductInfo = (inspection: ProductInspectionItem) => {
  const firstDetail = ensureFirstDetail();
  firstDetail.productName = inspection.productName || "";
  firstDetail.productNo = inspection.productCode || "";
  firstDetail.specification = inspection.specification || "";
  firstDetail.unit = inspection.unit || "";
  if (inspection.batchNo) {
    firstDetail.batchNo = inspection.batchNo;
    firstDetail.batch = inspection.batchNo;
  }
};

const handleInspectionConfirm = () => {
  if (!selectedInspection.value) {
    ElMessage.warning("请选择出货检验单");
    return;
  }
  formData.inspectionOrderId = selectedInspection.value.id;
  formData.inspectionOrderNo = selectedInspection.value.inspectionCode;
  formData.inspectionOrderName =
    selectedInspection.value.inspectionName ||
    selectedInspection.value.inspectionCode;
  applyInspectionProductInfo(selectedInspection.value);
  inspectionDialogVisible.value = false;
};

const formatInspectionDate = (
  row: ProductInspectionItem,
  _column: unknown,
  value: string | Date | null
) => {
  const target = value || row.inspectionDate || null;
  if (!target) return "-";
  return moment(target).format("YYYY-MM-DD");
};

const handleBatchConfirm = () => {
  if (currentBatchDetailIndex.value === null) {
    batchDialogVisible.value = false;
    return;
  }
  const batchRow =
    selectedBatchRow.value ||
    batchTableData.value.find((item) => item.id === selectedBatchId.value) ||
    null;
  if (!batchRow) {
    ElMessage.warning("请选择批次号");
    return;
  }
  const detail = ensureDetailAtIndex(currentBatchDetailIndex.value);
  detail.batchNoId = batchRow.id;
  detail.batchNo = batchRow.batchCode;
  detail.batch = batchRow.batchCode;
  const productionDate = formatBatchDate(batchRow.createTime);
  const expiryDate = formatBatchDate(batchRow.endTime);
  if (productionDate) {
    detail.productionDate = productionDate;
  }
  if (expiryDate) {
    detail.expiryDate = expiryDate;
  }
  batchDialogVisible.value = false;
};

const resetWarehouseDialogState = () => {
  warehouseSearchForm.warehouse = "";
  warehouseSearchForm.reservoir = "";
  warehouseSearchForm.seat = "";
  selectedWarehouseId.value = null;
  selectedReservoirId.value = null;
  selectedSeatId.value = null;
  selectedWarehouseOption.value = null;
  selectedReservoirOption.value = null;
  selectedSeatOption.value = null;
  reservoirOptions.value = [];
  seatOptions.value = [];
};

const fetchWarehouseOptions = async () => {
  warehouseListLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
    };
    if (warehouseSearchForm.warehouse.trim()) {
      params.Warehousenmae = warehouseSearchForm.warehouse.trim();
    }
    const res = await https.Reads.get("/Warehouse/WarehouseList", { params });
    const payload = res?.data ?? {};
    const rawList = Array.isArray(payload.data)
      ? payload.data
      : Array.isArray(payload.Data)
      ? payload.Data
      : [];
    warehouseOptions.value = rawList.map(normalizeWarehouseOption);
  } catch (error) {
    console.error("获取仓库列表失败:", error);
    warehouseOptions.value = [];
  } finally {
    warehouseListLoading.value = false;
  }
};

const fetchReservoirOptions = async () => {
  reservoirListLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
    };
    if (warehouseSearchForm.reservoir.trim()) {
      params.Reservoirnmae = warehouseSearchForm.reservoir.trim();
    }
    if (selectedWarehouseId.value) {
      params.Warehouseid = selectedWarehouseId.value;
    }
    const res = await https.Reads.get("/Warehouse/ReservoirList", { params });
    const payload = res?.data ?? {};
    const rawList = Array.isArray(payload.data)
      ? payload.data
      : Array.isArray(payload.Data)
      ? payload.Data
      : [];
    reservoirOptions.value = rawList.map(normalizeReservoirOption);
  } catch (error) {
    console.error("获取库区列表失败:", error);
    reservoirOptions.value = [];
  } finally {
    reservoirListLoading.value = false;
  }
};

const fetchSeatOptions = async () => {
  seatListLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
    };
    if (warehouseSearchForm.seat.trim()) {
      params.Seatnmae = warehouseSearchForm.seat.trim();
    }
    if (selectedWarehouseId.value) {
      params.Warehouseid = selectedWarehouseId.value;
    }
    if (selectedReservoirId.value) {
      params.Reservoirid = selectedReservoirId.value;
    }
    const res = await https.Reads.get("/Warehouse/Seatlist", { params });
    const payload = res?.data ?? {};
    const rawList = Array.isArray(payload.data)
      ? payload.data
      : Array.isArray(payload.Data)
      ? payload.Data
      : [];
    seatOptions.value = rawList.map(normalizeSeatOption);
  } catch (error) {
    console.error("获取库位列表失败:", error);
    seatOptions.value = [];
  } finally {
    seatListLoading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm("确认取消操作吗？未保存的数据将会丢失。", "确认取消", {
    type: "warning",
    confirmButtonText: "确认取消",
    cancelButtonText: "继续编辑",
  })
    .then(() => {
      router.push("/SalesOutboundList");
    })
    .catch(() => {
      // 用户选择继续编辑，不做任何操作
    });
};

onMounted(async () => {
  try {
    pageLoading.value = true;
    await initFormData();
  } catch (error) {
    console.error("页面初始化失败:", error);
    ElMessage.error("页面加载失败，请刷新重试");
  } finally {
    pageLoading.value = false;
  }
});
</script>

<style scoped>
.sales-outbound-add-page {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-bottom: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.breadcrumb-card {
  border-radius: 14px;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border: none;
  color: #fff;
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.25);
}

.breadcrumb-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.breadcrumb-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.breadcrumb-icon {
  font-size: 32px;
  color: #fff;
}

.breadcrumb-heading {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
}

.breadcrumb-subtitle {
  margin: 0;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.sales-outbound-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.content-layout {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 320px;
  gap: 20px;
  align-items: flex-start;
}

.content-main {
  min-width: 0;
}

.content-aside {
  display: flex;
  flex-direction: column;
  gap: 20px;
  position: sticky;
  top: 90px;
}

.insight-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 20px 50px rgba(15, 76, 129, 0.08);
}

.progress-card .card-icon {
  color: #34d399;
}

.highlight-card .card-icon {
  color: #f59e0b;
}

.tips-card .card-icon {
  color: #64748b;
}

.progress-body {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.progress-info {
  flex: 1;
}

.progress-value {
  margin: 0;
  font-size: 30px;
  font-weight: 700;
  color: #1f2d3d;
}

.progress-text {
  margin: 4px 0 0;
  font-size: 13px;
  color: #909399;
}

.checklist {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.checklist-item {
  display: flex;
  gap: 12px;
  padding: 10px 12px;
  border-radius: 14px;
  background: linear-gradient(135deg, #f8fafc, #f1f5f9);
  border: 1px dashed transparent;
  transition: all 0.2s ease;
}

.checklist-item.done {
  background: rgba(52, 211, 153, 0.12);
  border-color: rgba(52, 211, 153, 0.4);
}

.checklist-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.checklist-icon.success {
  color: #34d399;
}

.checklist-icon.pending {
  color: #f59e0b;
}

.checklist-label {
  margin: 0;
  font-weight: 600;
  color: #303133;
}

.checklist-desc {
  margin: 2px 0 0;
  font-size: 12px;
  color: #909399;
}

.highlight-list {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}

.highlight-item {
  padding: 12px 14px;
  border-radius: 14px;
  background: #f5f7fb;
  border: 1px solid #e4e9f2;
}

.highlight-label {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.highlight-value {
  margin: 4px 0 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
  word-break: break-all;
}

.tips-alert {
  margin-bottom: 12px;
}

.tips-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.tips-list li {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
}

.tips-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4facfe, #34d399);
  margin-top: 6px;
  flex-shrink: 0;
}

.status-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
}

.status-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 18px 20px;
  border-radius: 14px;
  background: #fff;
  border: 1px solid rgba(79, 172, 254, 0.15);
  box-shadow: 0 10px 25px rgba(79, 172, 254, 0.08);
}

.status-card__icon {
  width: 52px;
  height: 52px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 22px;
  color: #fff;
  background: linear-gradient(135deg, #6a8dff, #5ac8fa);
}

.status-card__icon.success {
  background: linear-gradient(135deg, #30cfd0, #38f9d7);
}

.status-card__icon.warning {
  background: linear-gradient(135deg, #f8d800, #fdeb71);
  color: #6c4c00;
}

.status-card__label {
  margin: 0;
  font-size: 13px;
  color: #909399;
}

.status-card__value {
  margin: 2px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.status-card__hint {
  font-size: 13px;
  color: #909399;
}

.steps-card {
  border-radius: 14px;
  border: none;
  background: linear-gradient(135deg, #eef7ff 0%, #ffffff 65%);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
}

.steps-card :deep(.el-step__title) {
  font-weight: 600;
}

.steps-card :deep(.el-step__description) {
  font-size: 13px;
  color: #7a8aa5;
}

.steps-card :deep(.el-step__head.is-process) {
  border-color: #409eff;
  color: #409eff;
}

.steps-card :deep(.el-step__head.is-finish) {
  border-color: #34d399;
  color: #34d399;
}

.form-card {
  border-radius: 14px;
  border: none;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background: #fff;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-icon {
  font-size: 18px;
  color: #4facfe;
}

.basic-info-wrapper {
  padding-top: 4px;
}

.basic-form-item {
  margin-bottom: 18px;
}

.basic-form-item :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.required-label {
  color: #f56c6c;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.inline-switch-field {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.inline-switch-field .basic-form-item {
  margin-bottom: 0;
  flex: 1;
}

.inline-switch {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #606266;
}

.inline-switch__text {
  min-width: 72px;
}

.inline-copy {
  padding: 0 4px;
}

.detail-panel {
  border: 1px solid #ebeef5;
  border-radius: 14px;
  padding: 24px;
  background: linear-gradient(180deg, #fff, #f8fbff);
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.6);
}

.detail-panel__header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 12px;
}

.detail-panel__title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2d3d;
}

.detail-panel__desc {
  margin: 4px 0 0;
  font-size: 13px;
  color: #909399;
}

.detail-panel__summary {
  padding: 6px 14px;
  border-radius: 999px;
  background: rgba(79, 172, 254, 0.12);
  color: #156bc1;
  font-weight: 600;
  font-size: 13px;
}

.detail-grid {
  --el-form-label-font-size: 14px;
}

.detail-grid.compact :deep(.el-form-item) {
  margin-bottom: 12px;
}

.detail-form-item :deep(.el-form-item__label) {
  font-weight: 500;
  color: #5c6c7b;
}

.detail-empty {
  border: 1px dashed #c0c4cc;
  border-radius: 12px;
  padding: 24px 0;
  background: #fafbff;
}

.form-actions-affix {
  width: 100%;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 18px 32px;
  border-radius: 16px;
  background: rgba(255, 255, 255, 0.96);
  border: 1px solid rgba(229, 233, 242, 0.8);
  box-shadow: 0 25px 40px rgba(64, 158, 255, 0.15);
  backdrop-filter: blur(6px);
}

.form-actions .el-button {
  min-width: 120px;
  padding: 12px 24px;
  border-radius: 10px;
  font-weight: 600;
}

.inspection-dialog :deep(.el-dialog__body) {
  padding-top: 10px;
}

.inspection-search {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr)) 1fr auto;
  gap: 12px;
  margin-bottom: 16px;
}

.inspection-search__actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.inspection-table {
  margin-bottom: 16px;
}

.inspection-product-cell {
  display: flex;
  flex-direction: column;
  line-height: 1.4;
}

.inspection-product-cell .product-code {
  font-size: 12px;
  color: #909399;
}

.inspection-pagination {
  display: flex;
  justify-content: flex-end;
}

.customer-search {
  display: grid;
  grid-template-columns: minmax(0, 1fr) auto;
  gap: 12px;
  margin-bottom: 16px;
}

.customer-search__actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.customer-table {
  margin-bottom: 16px;
}

.customer-pagination {
  display: flex;
  justify-content: flex-end;
}

.batch-dialog-toolbar {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 16px;
}

.batch-dialog-toolbar .el-input {
  flex: 1;
}

.batch-dialog-toolbar__actions {
  display: flex;
  gap: 8px;
}

.batch-dialog-table {
  margin-bottom: 16px;
}

.batch-dialog-pagination {
  display: flex;
  justify-content: flex-end;
}

.warehouse-dialog :deep(.el-dialog__body) {
  padding-top: 12px;
}

.warehouse-summary {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 10px;
  margin-bottom: 16px;
  font-size: 14px;
  color: #303133;
}

.warehouse-selector {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}

.selector-column {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.selector-column__header {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.selector-column__title {
  font-weight: 600;
  color: #303133;
}

.selector-column__list {
  border: 1px solid #e4e7ed;
  border-radius: 10px;
  padding: 8px;
  min-height: 280px;
  background: #fff;
}

.selector-item {
  padding: 10px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #606266;
  border: 1px solid transparent;
}

.selector-item + .selector-item {
  margin-top: 6px;
}

.selector-item:hover {
  background: #f0f7ff;
  color: #2474f5;
}

.selector-item.active {
  background: #e8f3ff;
  border-color: #409eff;
  color: #1d5fd0;
  font-weight: 600;
}

.warehouse-dialog :deep(.el-empty) {
  padding: 24px 0;
}

@media (max-width: 1024px) {
  .content-layout {
    grid-template-columns: 1fr;
  }

  .content-aside {
    position: static;
  }

  .warehouse-selector {
    grid-template-columns: 1fr;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-aside {
    order: -1;
  }

  .breadcrumb-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }

  .form-actions .el-button {
    width: 100%;
  }

  .inspection-search {
    grid-template-columns: 1fr;
  }

  .basic-info-wrapper :deep(.el-col) {
    flex: 0 0 100% !important;
    max-width: 100% !important;
  }

  .customer-search {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 600px) {
  .highlight-list {
    grid-template-columns: 1fr;
  }
}
</style>
